package naga.x.resource.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WindowsShutdownListener implements Runnable {
	
	private static Logger LOG;
	
	private WindowsShutdownListener() {
		LOG = LoggerFactory.getLogger(WindowsShutdownListener.class);
	}

	public static void listen() {
		if (System.getProperty("os.name").toLowerCase().contains("windows")) {
			new Thread(new WindowsShutdownListener()).start();
		}
	}

	@Override
	public void run() {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			while (true) {
				String cmd = reader.readLine();
				if ("exit".equals(cmd)) {
					break;
				}
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {}
			}
			System.exit(0);
			LOG.info("[WINDOWS SHUTDOWN]SUCC");
		} catch (Exception e) {
			LOG.error("[WINDOWS SHUTDOWN]FAIL", e);
		} finally {
			IOUtils.closeQuietly(reader);
		}
	}
	
}
